﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using Corsat.Library.DataManager;
using Corsat.Library.Logic;

namespace Corsat.Web._2013.Administration
{
    public partial class Questions : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                List<Library.Item> CourseNames =
                    Corsat.Library.DataManager.Main.GetAllItemsByCategory(Library.DataManager.Category.CourseNames);
                CourseNames.Insert(0, new Library.Item());
                ddlCourseNames.DataSource = CourseNames;
                ddlCourseNames.DataTextField = "Value";
                ddlCourseNames.DataValueField = "Id";
                ddlCourseNames.DataBind();
            }
        }


        protected void ddlCourseNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Load Course Levels
            List<Library.Item> CourseLevels =
                Corsat.Library.DataManager.Main.GetCourseLevels(Convert.ToInt32(ddlCourseNames.SelectedValue));
            rdoLevel.DataSource = CourseLevels;
            rdoLevel.DataTextField = "Value";
            rdoLevel.DataValueField = "Id";
            rdoLevel.DataBind();
            if (CourseLevels.Any())
            {
                hdnSelectedCourseId.Value = string.Empty;   
            }
            else
            {
                hdnSelectedCourseId.Value = GetCourseId(Convert.ToInt32(ddlCourseNames.SelectedValue), 0).ToString();
            }
            loadQuestions();
        }

        private int GetCourseId(int CourseTitleId, int courseLevelId)
        {
            // if session doesn't have "dtCourses" datatable .. get all courses and store them in the session object
            if (Session["dtCourses"] == null)
            {
                // Get all Courses
                DataTable dtCourses = Main.GetAllCoursesWithDates();
                if (dtCourses == null)
                    return 0;

                // Store datatable in the session object
                if (dtCourses != null && Session["dtCourses"] == null)
                    Session.Add("dtCourses", dtCourses);
            }

            DataRow[] dr;
            // select Course Id from Session["dtCourses"] data Table
            if (courseLevelId == 0)
                dr =
                    ((DataTable) Session["dtCourses"]).Select("CourseTitleId =" + CourseTitleId +
                                                              " AND CourseLevelId IS NULL ");
            else
                dr =
                    ((DataTable) Session["dtCourses"]).Select("CourseTitleId =" + CourseTitleId + " AND CourseLevelId =" +
                                                              courseLevelId);

            if (dr.Length > 0)
                return (Convert.ToInt32(dr[0]["CourseId"]));
            else
                return 0;

        }

        protected void btnLoad_Click(object sender, EventArgs e)
        {
            loadQuestions();
        }

        private void loadQuestions()
        {
            // if No Course Title selected
            // OR (a Course Title is selected AND Course Has Levels but none is selected)
            // Clear Absence Grid
            if (ddlCourseNames.SelectedValue == "" ||
                (ddlCourseNames.SelectedValue != "" && rdoLevel.Items.Count > 0 && rdoLevel.SelectedIndex == -1))
            {
                grdQuestions.DataSource = null;
                grdQuestions.DataBind();
                return;
            }


            // Get Course Level Id
            int courseLeveId = 0;
            if (rdoLevel != null && rdoLevel.SelectedValue != "")
                courseLeveId = Convert.ToInt32(rdoLevel.SelectedValue);

            // Get Course Id
            int courseId = GetCourseId(Convert.ToInt32(ddlCourseNames.SelectedValue), courseLeveId);

            // Get Absence Data
            DataTable dtAbsence = Main.GetCourseQuestions(courseId);

            // Set Grid Data Source and rebind
            pnlAccountsInCourse.Visible = true;
            grdQuestions.DataSource = dtAbsence;
            grdQuestions.DataBind();
        }

        protected void rdoLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get Course Level Id
            int courseLeveId = 0;
            if (rdoLevel != null && rdoLevel.SelectedValue != "")
                courseLeveId = Convert.ToInt32(rdoLevel.SelectedValue);
            // Get Course Id
            int courseId = GetCourseId(Convert.ToInt32(ddlCourseNames.SelectedValue), courseLeveId);
            hdnSelectedCourseId.Value = courseId.ToString();
        }

        protected void BtnSearch_Clicked(object sender, EventArgs e)
        {
            /*var account = Main.GetAccountBySSN(txtAccountSSN.Text);
            if (account != null && account.AccountId > 0)
            {

                Session["accountId"] = account.AccountId;
                Session["CorsatId"] = account.CorsatId;
                Response.Redirect("Profile.aspx");
            }
            else
            {
                lblError.Visible = true;
            }*/
        }


        [WebMethod]
        public static object GetDate(string questionId)
        {
            int qId = 0;
            if (!string.IsNullOrWhiteSpace(questionId) && int.TryParse(questionId, out qId) && qId > 0)
            {
                Question question = Main.GetCourseQuestionData(qId);

                if (question != null)
                {
                    return new {questionId,question.CourseId , question.Text,question.QuestionLevelId, question.Answers};
                }
            }

            var response = new {firstname = "John " + questionId, lastname = "Smith"};
            return response;
        }

        [WebMethod]
        public static void Save(Question question)
        {
            //question.QuestionLevelId = 1;

            Main.SaveCourseQuestion(question);

        }


        [WebMethod]
        public static object DeleteQuestion(string questionId)
        {
            bool result = false;
            int qId = 0;
            if (!string.IsNullOrWhiteSpace(questionId) && int.TryParse(questionId, out qId) && qId > 0)
            {
                result = Main.DeleteQuestion(qId);
            }
            return  new { result};
        }
    }
}